package com.ishowcode.controller.FileController;
import com.ishowcode.annotation.GlobalInterceptor;
import com.ishowcode.entity.*;
import com.ishowcode.service.FileInfoService;
import com.ishowcode.service.MessageInfoService;
import com.ishowcode.service.UserInfoService;
import com.ishowcode.utils.BizException;
import com.ishowcode.utils.RedisUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class FileInfoController {
    String userkey ="user--";
    ApplicationHome applicationHome = new ApplicationHome(this.getClass());
    String path = applicationHome.getDir().getParentFile()
            .getParentFile().getAbsolutePath();
//    String path = "/summer/easycloud/upload";
    @Resource
    RedisUtil redisUtil;
    @Resource
    UserInfoService userInfoService;
    @Resource
    MessageInfoService messageInfoService;
    @Resource
    FileInfoService fileInfoService;
    @RequestMapping("/uploadfile")
    @GlobalInterceptor(checkParam = true,checkLogin = true)
    public Result uploadFile(@RequestParam("email")String email,@RequestParam("files") MultipartFile[] files,@RequestParam("fileIds") List<String> fileIds){
        if (fileIds.size()>1) return Result.failure(ResultCode.fileupload_error);
        String filePid = "";
        if (fileIds.size()==0) filePid="0";
        else {
            if (fileInfoService.getFileById(fileIds.get(0)).getFolderType()==0) return Result.failure("请勾选文件夹存放");
            else filePid = fileInfoService.getFileById(fileIds.get(0)).getFileId();
        }
        Boolean isNull = false;
        try {
            isNull = files.length>0?true:false;
        }catch (BizException e){
            e.setR(ResultCode.File_Upload_Error);
        }
        User user = (User) redisUtil.get(userkey + email);
        if (null==user){
            return Result.failure();
        }
        if (isNull){
            for (MultipartFile file1 :files){
                if (!file1.isEmpty()){
                    if (user.getTotalSpace()<(user.getUseSpace()+file1.getSize())) return Result.failure(ResultCode.File_Space_Error);
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    Filebean file = new Filebean();
                    file.setFileId(uuid);
                    file.setUserId(user.getUserId());
                    file.setFileSize(file1.getSize());
                    Calendar ca = Calendar.getInstance();
                    Date dNow = ca.getTime();
                    file.setCreateTime(dNow);
                    file.setFolderType((short) 0);
                    file.setDelFlag((short) 2);
                    file.setFilePid(filePid);
                    file.setFolderType((short) 0);
                    String orginFilename = file1.getOriginalFilename();
                    String type = orginFilename.substring(orginFilename.indexOf(".")+1);
                    if(type.equals("mp4")||type.equals("3gp")||type.equals("avi")||type.equals("wmv")||type.equals("mpeg")||type.equals("mpg")||type.equals("mov")||type.equals("flv")||type.equals("swf")||type.equals("qsv")||type.equals("kux")||type.equals("mpg")){
                        file.setFileType((short) 1);
                    }else if(type.equals("jpg")||type.equals("jpeg")||type.equals("png")||type.equals("ico")||type.equals("svg")||type.equals("gif")||type.equals("svgz")||type.equals("tif")){
                        file.setFileType((short) 3);
                    }else if(type.equals("mp3")||type.equals("mp2")||type.equals("mp1")||type.equals("wav")||type.equals("aif")||type.equals("aiff")||type.equals("ram")||type.equals("mid")){
                        file.setFileType((short) 2);
                    }else if(type.equals("txt")||type.equals("doc")||type.equals("docx")||type.equals("xls")||type.equals("xlsx")||type.equals("pptx")||type.equals("ppt")||type.equals("pdf")){
                        file.setFileType((short) 4);
                    }else {
                        file.setFileType((short) 5);
                    }
                    if (null!=fileInfoService.getFileByName(orginFilename)){
                        String substring = orginFilename.substring(0, orginFilename.indexOf("."));
                        orginFilename = substring+uuid.substring(0,6)+orginFilename.substring(orginFilename.indexOf("."));
                    }
                    file.setFileName(orginFilename);
                    try {
                        file1.transferTo(new File(path+orginFilename));
                    } catch (BizException e) {
                        e.setR(ResultCode.File_Upload_Error);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (fileInfoService.getFileById(filePid)!=null){
                        Stack<Filebean> willmovefilepidStack= new Stack<>();
                        getallpidfolder(willmovefilepidStack,filePid);
                        willmovefilepidStack.push(fileInfoService.getFileById(filePid));
                        int moveSize = willmovefilepidStack.size();
                        for (int j = 0; j <moveSize; j++) {
                            Filebean pop = willmovefilepidStack.pop();
                            pop.setFileSize(pop.getFileSize()+file.getFileSize());
                            System.out.println(pop.getFileName()+"----"+"增加了"+file.getFileSize()+"B");
                            Integer integer = fileInfoService.updatefileById(pop);
                            if (integer<=0) return Result.failure(ResultCode.Data_Error);
                        }
                    }

                    Integer integer = fileInfoService.addFile(file);
                    User user1 = userInfoService.queryUserByEmail(email);
                    user1.setUseSpace(user1.getUseSpace()+file.getFileSize());
                    Integer integer1 = userInfoService.updateUser(user1);
                    redisUtil.set(userkey+user1.getEmail(),user1);
                    redisUtil.expire(userkey+user1.getEmail(),3600);
                    //
                    Message message = new Message();
                    String uuid1 = UUID.randomUUID().toString().replaceAll("-", "");
                    message.setMessageId(uuid1);
                    message.setUserId(user.getUserId());
                    Calendar ca1 = Calendar.getInstance();
                    Date dNow1 = ca1.getTime();
                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    message.setCreateTime(dNow);
                    message.setMessageContent("您于:"+ft.format(dNow1)+"上传了"+file.getFileName());
                    messageInfoService.addMessage(message);
                    //
                    if (integer<=0||integer1<=0){
                        Result.failure(ResultCode.Data_Error);
                    }
                }
            }
        }
        return Result.success();

    }
    @RequestMapping("/getFileInfo")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getFileInfo(@RequestParam("email") String email,@RequestParam("input")String input){
        HashMap<String, List> dataMap = new HashMap<>();
        List<Filebean> fileList;
        String userId = ((User) redisUtil.get(userkey+email)).getUserId();
        try {
            fileList= fileInfoService.getFileByMohu(userId,input);
        }catch (BizException e){
            e.setR(ResultCode.INTERNAL_SERVER_ERROR);
            throw e;
        }
        dataMap.put("fileList",fileList);
        return Result.success(dataMap);
    }

    @RequestMapping("/getbackByPid")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getbackByPid(@RequestParam("email") String email,@RequestParam("pid")String pid){
        if ("0".equals(pid))return Result.failure("已经是根目录啦~");
        HashMap<String, List> dataMap = new HashMap<>();
        List<Filebean> fileList = null;
        String userId = ((User) redisUtil.get(userkey+email)).getUserId();
        try {
            Filebean gobackfile = fileInfoService.getFileById(pid);
            fileList = fileInfoService.getFileByPid(userId, gobackfile.getFilePid());
        }catch (BizException e){
            e.setR(ResultCode.INTERNAL_SERVER_ERROR);
        }
        dataMap.put("fileList",fileList);
        return Result.success(dataMap);
    }
    @RequestMapping("/getFileInfoByPid")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getFileInfoByPid(@RequestParam("email") String email,@RequestParam("pid")String pid){
        HashMap<String, List> dataMap = new HashMap<>();
        List<Filebean> fileList = null;
        String userId = ((User) redisUtil.get(userkey+email)).getUserId();
        try {
            fileList = fileInfoService.getFileByPid(userId, pid);
        }catch (BizException e){
            e.setR(ResultCode.INTERNAL_SERVER_ERROR);
        }
        dataMap.put("fileList",fileList);
        return Result.success(dataMap);
    }
    @RequestMapping("/createFloder")
    @GlobalInterceptor(checkParam = true,checkLogin = true)
    public Result createFloder(@RequestParam("email")String email,@RequestParam("flodername") String flodername){
        User user = (User) redisUtil.get(userkey + email);
        if (null==user){
            return Result.failure();
        }
        Filebean file = new Filebean();
        if (null==fileInfoService.getFileByName(flodername)){
            file.setFileName(flodername);
        }else {
            return Result.failure(ResultCode.floder_name_error);
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        file.setFileId(uuid);
        file.setUserId(user.getUserId());
        file.setFileSize(0L);
        file.setFolderType((short) 1);
        file.setFileType((short) 6);
        Calendar ca = Calendar.getInstance();
        Date dNow = ca.getTime();
        file.setCreateTime(dNow);
        file.setDelFlag((short) 2);
        file.setFilePid("0");
        Integer integer;
        try {
            integer  = fileInfoService.addFile(file);
        }catch (BizException e){
            e.setR(ResultCode.File_Upload_Error);
            throw  e;
        }
        if (integer>=1){
            return Result.success();
        }else
            return Result.failure("创建文件夹失败");
    }
    @RequestMapping("/deleteById")
    @GlobalInterceptor(checkLogin = true)
    public Result deleteById(@RequestParam("email") String email,@RequestParam("fileIds") List<String> fileIds){
        if (fileIds.size()<=0)return Result.failure("未勾选要删除的文件");
        String filePath;
        for (int i = 0; i <fileIds.size() ; i++) {
            Filebean file = fileInfoService.getFileById(fileIds.get(i));
            if (file.getFilePid().equals("0")){
                if (file.getFolderType()==1){
                    Stack<Filebean> willdeletefilepidStack = new Stack<>();
                    getallsidfloder(willdeletefilepidStack,fileIds.get(i));
                    willdeletefilepidStack.push(fileInfoService.getFileById(fileIds.get(i)));
                    int deleteSize = willdeletefilepidStack.size();
                    for (int j = 0; j <deleteSize; j++) {
                        Filebean pop = willdeletefilepidStack.pop();
                        if (pop.getFolderType()==0){
                            filePath=path+pop.getFileName();
                            Integer integer = fileInfoService.deleteByFileId(pop.getFileId());
                            if (integer<=0) return Result.failure(pop.getFileName()+"删除失败");
                            User user = userInfoService.queryUserByEmail(email);
                            user.setUseSpace(user.getUseSpace()-pop.getFileSize());
                            userInfoService.updateUser(user);
                            redisUtil.set(userkey+email,user);
                            File file1 = new File(filePath);
                            boolean isdelete = file1.delete();
                            if (!isdelete) return Result.failure(file.getFileName()+"删除失败");
                            //
                            Message message = new Message();
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            message.setMessageId(uuid);
                            message.setUserId(user.getUserId());
                            Calendar ca = Calendar.getInstance();
                            Date dNow = ca.getTime();
                            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            message.setCreateTime(dNow);
                            message.setMessageContent("您于:"+ft.format(dNow)+"删除了 "+pop.getFileName());
                            messageInfoService.addMessage(message);
                            //
                        }else {
                            Integer integer = fileInfoService.deleteByFileId(pop.getFileId());
                            if (integer<=0) return Result.failure(pop.getFileName()+"删除失败");
                        }
                    }
                }else {
                    filePath=path+file.getFileName();
                    Integer integer = fileInfoService.deleteByFileId(fileIds.get(i));
                    if (integer<=0) return Result.failure(file.getFileName()+"删除失败");
                    User user = userInfoService.queryUserByEmail(email);
                    user.setUseSpace(user.getUseSpace()-file.getFileSize());
                    userInfoService.updateUser(user);
                    redisUtil.set(userkey+email,user);
                    File file1 = new File(filePath);
                    boolean isdelete = file1.delete();
                    if (!isdelete) return Result.failure(file.getFileName()+"删除失败");
                }
            }else {
                Stack<Filebean> willRemovefilepidStack = new Stack<>();
                getallpidfolder(willRemovefilepidStack,fileIds.get(i));
                int RemoveSize = willRemovefilepidStack.size();
                for (int j = 0; j <RemoveSize; j++) {
                    Filebean pop = willRemovefilepidStack.pop();
                    pop.setFileSize(pop.getFileSize()-file.getFileSize());
                    Integer integer = fileInfoService.updatefileById(pop);
                    if (integer<=0) return Result.failure(ResultCode.Data_Error);
                }
                Stack<Filebean> willdeletefilepidStack = new Stack<>();
                getallsidfloder(willdeletefilepidStack,fileIds.get(i));
                willdeletefilepidStack.push(fileInfoService.getFileById(fileIds.get(i)));
                int deleteSize = willdeletefilepidStack.size();
                for (int j = 0; j <deleteSize; j++) {
                    Filebean pop = willdeletefilepidStack.pop();
                    if (pop.getFolderType()==0){
                        filePath=path+pop.getFileName();
                        Integer integer = fileInfoService.deleteByFileId(pop.getFileId());
                        if (integer<=0) return Result.failure(pop.getFileName()+"删除失败");
                        User user = userInfoService.queryUserByEmail(email);
                        user.setUseSpace(user.getUseSpace()-pop.getFileSize());
                        userInfoService.updateUser(user);
                        redisUtil.set(userkey+email,user);
                        File file1 = new File(filePath);
                        boolean isdelete = file1.delete();
                        if (!isdelete) return Result.failure(file.getFileName()+"删除失败");
                    }else {
                        Integer integer = fileInfoService.deleteByFileId(pop.getFileId());
                        if (integer<=0) return Result.failure(pop.getFileName()+"删除失败");
                    }
                }
            }
        }
        return Result.success();
    }

    public void getallsidfloder(Stack<Filebean> stack,String fileId){
        Filebean file = fileInfoService.getFileById(fileId);
        List<Filebean> fileByPid = fileInfoService.getFileByPid(file.getUserId(), fileId);
        if (fileByPid.size()<=0) return;
        for (int i = 0; i < fileByPid.size() ; i++) {
            if (fileByPid.get(i).getFolderType()==0){
                stack.push(fileByPid.get(i));
            }else {
                stack.push(fileByPid.get(i));
                getallsidfloder(stack,fileByPid.get(i).getFileId());
            }
        }

    }
    @RequestMapping("/getfolder")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getfolder(@RequestParam("email")String email){
        User user = (User) redisUtil.get(userkey + email);
        if (null==user){
            return Result.failure();
        }
        List<Filebean> folder = null;
        try {
            folder  =fileInfoService.getFloderByUserId(user.getUserId());
        }catch (BizException e){
            e.setR(ResultCode.FAILURE);
        }


        return Result.success(folder);
    }
    public void getallpidfolder(Stack<Filebean> filebeanStack,String fileid){
        Filebean file = fileInfoService.getFileById(fileid);
        if (file.getFilePid().equals("0")) return;
        if (fileInfoService.getFileById(file.getFilePid()).getFolderType()==1) filebeanStack.push(fileInfoService.getFileById(file.getFilePid()));
        else return;
        getallpidfolder(filebeanStack,file.getFilePid());
        return;
    }
    @RequestMapping("/moveapplication")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result moveapplication(@RequestParam("email")String email,@RequestParam("fileIds") List<String> fileIds,@RequestParam("pid")String pid){
        if (fileIds.size()<=0)return Result.failure("未勾选要移动的文件");
        if (pid.equals("-1")){
            for (int i = 0; i <fileIds.size() ; i++) {
                Filebean file = fileInfoService.getFileById(fileIds.get(i));
                Stack<Filebean> willRemovefilepidStack = new Stack<>();
                getallpidfolder(willRemovefilepidStack,fileIds.get(i));
                int RemoveSize = willRemovefilepidStack.size();
                for (int j = 0; j <RemoveSize; j++) {
                    Filebean pop = willRemovefilepidStack.pop();
                    pop.setFileSize(pop.getFileSize()-file.getFileSize());
                    System.out.println(pop.getFileName()+"----"+"减少了"+file.getFileSize()+"B");
                    Integer integer = fileInfoService.updatefileById(pop);
                    if (integer<=0) return Result.failure(ResultCode.Data_Error);
                }
                file.setFilePid("0");
                Integer integer = fileInfoService.updatefileById(file);
                if (integer<=0) return Result.failure(ResultCode.Data_Error);
            }
        }else {
            for (int i = 0; i <fileIds.size() ; i++) {
                Filebean file = fileInfoService.getFileById(fileIds.get(i));
                Stack<Filebean> willRemovefilepidStack = new Stack<>();
                getallpidfolder(willRemovefilepidStack,fileIds.get(i));
                int RemoveSize = willRemovefilepidStack.size();
                for (int j = 0; j <RemoveSize; j++) {
                    Filebean pop = willRemovefilepidStack.pop();
                    pop.setFileSize(pop.getFileSize()-file.getFileSize());
                    System.out.println(pop.getFileName()+"----"+"减少了"+file.getFileSize()+"B");
                    Integer integer = fileInfoService.updatefileById(pop);
                    if (integer<=0) return Result.failure(ResultCode.Data_Error);
                }
                Stack<Filebean> willmovefilepidStack= new Stack<>();
                getallpidfolder(willmovefilepidStack,pid);
                willmovefilepidStack.push(fileInfoService.getFileById(pid));
                int moveSize = willmovefilepidStack.size();
                for (int j = 0; j <moveSize; j++) {
                    Filebean pop = willmovefilepidStack.pop();
                    pop.setFileSize(pop.getFileSize()+file.getFileSize());
                    System.out.println(pop.getFileName()+"----"+"增加了"+file.getFileSize()+"B");
                    Integer integer = fileInfoService.updatefileById(pop);
                    if (integer<=0) return Result.failure(ResultCode.Data_Error);
                }
                file.setFilePid(pid);
                Integer integer = fileInfoService.updatefileById(file);
                if (integer<=0) return Result.failure(ResultCode.Data_Error);

            }
        }
        return Result.success();
    }
    @RequestMapping("/getFileByType")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getFileByType(@RequestParam("email")String email,@RequestParam("type")String fileType,@RequestParam("input")String input){
        HashMap<String, List> dataMap = new HashMap<>();
        List<Filebean> fileList = null;
        String userId = ((User) redisUtil.get(userkey+email)).getUserId();
        try {
            fileList = fileInfoService.getFileByType(userId,fileType,input);
        }catch (BizException e){
            e.setR(ResultCode.INTERNAL_SERVER_ERROR);
        }
        dataMap.put("fileList",fileList);
        return Result.success(dataMap);

    }
@RequestMapping("/downloadByfileId")
@GlobalInterceptor(checkParam = true,checkLogin = true)
public ResponseEntity<ByteArrayResource> downloadByfileId(@RequestParam("email")String email, @RequestParam("fileId")String fileId) throws IOException {
    Filebean file = fileInfoService.getFileById(fileId);
    if (file==null){
        return (ResponseEntity<ByteArrayResource>) ResponseEntity.status(404);
    }else if(file.getFolderType()==1){
        // 创建一个字节数组输出流，用于生成zip文件
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        Stack<Filebean> willdeletefilepidStack = new Stack<>();
        getallsidfloder(willdeletefilepidStack,file.getFileId());
        int donum = willdeletefilepidStack.size();
        for (int i = 0; i <donum ; i++) {
            Filebean pop = willdeletefilepidStack.pop();
            // 将文件添加到zip中
            if(pop.getFolderType()==0){
                File file1 = new File(path + pop.getFileName());
                if (!file1.exists()) return (ResponseEntity<ByteArrayResource>) ResponseEntity.status(404);
                ZipEntry zipEntry = new ZipEntry(pop.getFileName());
                zipOutputStream.putNextEntry(zipEntry);
                Path path1 = Paths.get(path + pop.getFileName());
                byte[] bytes = Files.readAllBytes(path1);
                zipOutputStream.write(bytes);
                zipOutputStream.closeEntry();
            }
        }
        zipOutputStream.close();
        // 创建ByteArrayResource
        ByteArrayResource resource = new ByteArrayResource(byteArrayOutputStream.toByteArray());
        // 设置响应头，指定文件名
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+ URLEncoder.encode(file.getFileName()+".zip", "UTF-8"));
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(byteArrayOutputStream.size())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
    else{
        try {
            File file2 = new File(path + file.getFileName());
            if (!file2.exists()) return (ResponseEntity<ByteArrayResource>) ResponseEntity.status(404);
            FileInputStream fileInputStream = new FileInputStream(file2);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 创建ByteArrayResource
            ByteArrayResource resource = new ByteArrayResource(buffer);
            // 设置响应头，指定文件名
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+ URLEncoder.encode(file.getFileName(), "UTF-8"));
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(buffer.length)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);

        } catch (BizException e) {
            e.setR(ResultCode.filedownload_error);
            throw e;
        }
    }
}
    @RequestMapping("download")
    public ResponseEntity<ByteArrayResource> download( @RequestParam("fileId")String fileId)throws IOException{
        Filebean file = fileInfoService.getFileById(fileId);
        if (file==null){
            return (ResponseEntity<ByteArrayResource>) ResponseEntity.status(404);
        }else if(file.getFolderType()==1){
            // 创建一个字节数组输出流，用于生成zip文件
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
            Stack<Filebean> willdeletefilepidStack = new Stack<>();
            getallsidfloder(willdeletefilepidStack,file.getFileId());
            int donum = willdeletefilepidStack.size();
            for (int i = 0; i <donum ; i++) {
                Filebean pop = willdeletefilepidStack.pop();
                // 将文件添加到zip中
                if(pop.getFolderType()==0){
                    File file1 = new File(path + pop.getFileName());
                    if (!file1.exists()) return (ResponseEntity<ByteArrayResource>) ResponseEntity.status(404);
                    ZipEntry zipEntry = new ZipEntry(pop.getFileName());
                    zipOutputStream.putNextEntry(zipEntry);
                    Path path1 = Paths.get(path + pop.getFileName());
                    byte[] bytes = Files.readAllBytes(path1);
                    zipOutputStream.write(bytes);
                    zipOutputStream.closeEntry();
                }
            }
            zipOutputStream.close();
            // 创建ByteArrayResource
            ByteArrayResource resource = new ByteArrayResource(byteArrayOutputStream.toByteArray());
            // 设置响应头，指定文件名
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+file.getFileName()+".zip");
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(byteArrayOutputStream.size())
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        }
        else{
            try {
                File file2 = new File(path + file.getFileName());
                if (!file2.exists()) return (ResponseEntity<ByteArrayResource>) ResponseEntity.status(404);
                FileInputStream fileInputStream = new FileInputStream(file2);
                InputStream fis = new BufferedInputStream(fileInputStream);
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 创建ByteArrayResource
                ByteArrayResource resource = new ByteArrayResource(buffer);
                // 设置响应头，指定文件名
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+file.getFileName());
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentLength(buffer.length)
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);

            } catch (BizException e) {
                e.setR(ResultCode.filedownload_error);
                throw e;
            }
        }

    }
    @RequestMapping("/renameById")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result renameById(@RequestParam("email")String email, @RequestParam("fileId")String fileId,@RequestParam("rename")String rename){
        if (rename.equals(""))return Result.failure("文件名不能为空");
        Filebean file = fileInfoService.getFileById(fileId);
        String oldname = file.getFileName();
        if (null==file) return Result.failure("该文件不存在");
        Filebean fileByName = fileInfoService.getFileByName(rename);
        if (fileByName!=null) return Result.failure("该文件名已占用");
        if (file.getFolderType()==0){
            File file1 = new File(path+file.getFileName());
            if (!file1.exists())
            {
                return Result.failure("文件不存在");
            }
            else
            {
                file1.renameTo(new File(path+rename+file1.getName().substring(file1.getName().indexOf("."),file1.getName().length())));
                file.setFileName(rename+file1.getName().substring(file1.getName().indexOf("."),file1.getName().length()));
            }
        }else {
            file.setFileName(rename);
        }

        Integer integer = fileInfoService.updatefileById(file);
        //
        Message message = new Message();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        User user = userInfoService.queryUserByEmail(email);
        message.setMessageId(uuid);
        message.setUserId(user.getUserId());
        Calendar ca = Calendar.getInstance();
        Date dNow = ca.getTime();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        message.setCreateTime(dNow);
        message.setMessageContent("您于:"+ft.format(dNow)+"将"+oldname+" 的名称改为"+file.getFileName());
        messageInfoService.addMessage(message);
        //
        if (integer>=1)return Result.success();
        else return Result.failure("修改文件名称失败");


    }
}
